package com.m7788.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.example.qr_codescan.MipcaActivityCapture;
import com.m7788.dao.HUrlDaoImpl;
import com.m7788.dlg.SystemSetPop;
import com.m7788.po.HistoryUrl;
import com.m7788.screen.CustomCamera;
import com.m7788.screen.IndexScreen;
import com.m7788.screen.LoginScreen;
import com.m7788.screen.TakePhotoScreen;
import com.m7788.screen.aliapi.AliPayUtil;
import com.m7788.screen.wxapi.WXPayUtil;
import com.m7788.util.DialogChooseMenu.OnChoosePhotoListener;
import com.netease.LDNetDiagnoService.LDNetDiagnoListener;
import com.netease.LDNetDiagnoService.LDNetDiagnoService;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.tool.utils.DataUtil;
import com.tool.utils.StrUtils;

public class HtmlInterface implements OnChoosePhotoListener {
    private Context context;
    private Activity mactivity;
    private DialogChooseMenu dcm;
    private WebView webview;
    public static boolean isShare = false;
    public static final int REQUEST_CODE_ALUBM = 1;
    private SystemSetPop mSystemSetPop;
    private static final String TAG = "HtmlInterface";
    private int mCount;
    private String mDiagnoseLog = "";
    private boolean mIsChecking = false;
    private LDNetDiagnoService mLdDiagnoService;
//	private SubmitDialog mSubmitDialog;
//	private ArrayList<DiagnoseEntity> mDiagnoseList = new ArrayList<DiagnoseEntity>();

    public HtmlInterface(Context context, Activity aclass, WebView webview) {
        this.context = context;
        this.mactivity = aclass;
        this.webview = webview;
        dcm = new DialogChooseMenu(context, this);
        mSystemSetPop = new SystemSetPop(context);
//		mSubmitDialog = new SubmitDialog(context);
    }

    @JavascriptInterface
    public void app_pic_press(final String url) {
        FileDownloadUtil picDownloadUtil = new FileDownloadUtil(
                new FileDownloadUtil.DownLoadListener() {

                    @Override
                    public void downLoadSuccess() {
                        DataUtil.showShortToast(context, "图片保存成功");
                    }
                });
        picDownloadUtil.downFileFromUrl(context, url);
    }

    /**
     * 方法名：openMenu 功能： 参数：
     *
     * @param type 1：上传 2：修改
     * @param path 创建人：huanghaishui 创建时间：2013-8-12
     */
    @JavascriptInterface
    public void openMenu(int type, String path, int flag, int closeWater) {
        // webview.loadUrl("javascript:android.setfName(document.getElementById('fName').value);");
        AppUtil.saveRecord(context, Constant.TYPE, type + "");
        AppUtil.saveRecord(context, Constant.OPERATION, "1");
        AppUtil.saveRecord(context, Constant.PARAMS, path + "");
        AppUtil.saveRecord(context, Constant.FLAG, flag + "");
        AppUtil.saveRecord(context, Constant.CLOSE_WATER, (closeWater == 1) + "");

        // showToast(AppUtil.getRecord(context, Constant.FLAG));
        refreshImage(flag);
        // Log.e("params", path);

        // if(flag==2){
        // AppUtil.saveRecord(context, Constant.REFRESHWEB, "1");
        // Intent intent = new Intent(context, AlbumScreen.class);
        // context.startActivity(intent);
        // }else{
        // dcm.show(); //显示选择页面
        // }
    }

    @JavascriptInterface
    public void android_scroll_horizontal_ctrl(String params) {
        if (params.equals("0")) {
            Constant.sCanHorizontalMove = false;
        } else {
            Constant.sCanHorizontalMove = true;
        }
    }

    @JavascriptInterface
    public void android_scroll_all_ctrl(String params) {
        if (params.equals("0")) {
            Constant.sCanHorizontalMove = false;
        } else {
            Constant.sCanHorizontalMove = true;
        }
        AppUtil.sendMesToActivity(context, 466, params);
    }

    @JavascriptInterface
    public void show_menu() {
        dcm.show();
    }

    /**
     * 方法名：login 功能：登录 参数： 创建人：huanghaishui 创建时间：2013-8-12
     */
    @JavascriptInterface
    public void login() {
        Intent intent = new Intent(context, LoginScreen.class);
        intent.putExtra("key", "changeUser");
        context.startActivity(intent);
        mactivity.getParent().finish();
    }

    /**
     * 方法名：showToast 功能：提示 参数：
     *
     * @param message 创建人：huanghaishui 创建时间：2013-12-25
     */
    @JavascriptInterface
    public void showToast(String message) {
        DataUtil.showShortToast(context, message);
    }

    /**
     * 方法名：getToken 功能： 参数：
     *
     * @return 创建人：huanghaishui 创建时间：2013-8-12
     */
    @JavascriptInterface
    public String getToken() {
        return  AppUtil.getToken(context);
    }

    @JavascriptInterface
    public void showSource(String html) {
        // Log.e("HTML", html);
        String url = AppUtil.getRecord(context, Constant.TEMP_URL);
        if (url.length() > 0) {
            HUrlDaoImpl daoImpl = new HUrlDaoImpl(context);
            HistoryUrl hu = new HistoryUrl(url, html);
            daoImpl.insert(hu);
        }

    }

    /**
     * 图片选择
     */
    @JavascriptInterface
    private void selectImage() {
        Intent intent = new Intent(context,
                MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        // 最大可选择图片数量
        String params;// 参数集合
        params = AppUtil.getRecord(context,Constant.PARAMS);
        Map<String, String> parmasMap = new HashMap<String, String>();
        if (params.length() > 0) {
            parmasMap = AppUtil.combineHttpParams(params);
            String fnum = parmasMap.get("num");
            String fmax = parmasMap.get("max_num");
            if (fnum != null && fmax != null) {
                int re = Integer.valueOf(fmax) - Integer.valueOf(fnum);
                intent.putExtra(
                        MultiImageSelectorActivity.EXTRA_SELECT_COUNT, re);
            } else {
                intent.putExtra(
                        MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 10);
            }
        } else {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT,
                    10);
        }
        if (AppUtil.getRecord(context, Constant.TYPE).equals("1")) {
            // 选择模式
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE,
                    MultiImageSelectorActivity.MODE_MULTI);
        } else if (AppUtil.getRecord(context, Constant.TYPE).equals("2")) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE,
                    MultiImageSelectorActivity.MODE_SINGLE);
        }
        ((Activity) context).startActivityForResult(intent,
                REQUEST_CODE_ALUBM);
    }

    @Override
    public void refreshImage(int flag) {
        if (flag == 3) {
            AppUtil.saveRecord(context, Constant.REFRESHWEB, "1");
            selectImage();
            // Intent intent = new Intent(context, AlbumScreen.class);
            // context.startActivity(intent);
        } else if (flag == 1) {
            AppUtil.saveRecord(context, Constant.REFRESHWEB, "1");
            // Intent intent = new Intent(context, TakePhotoScreen.class);
            Intent intent = new Intent(context, CustomCamera.class);
            context.startActivity(intent);
        } else if (flag == 2) {
            AppUtil.saveRecord(context, Constant.REFRESHWEB, "1");
            Intent intent = new Intent(context, TakePhotoScreen.class);
            // Intent intent = new Intent(context, CustomCamera.class);
            context.startActivity(intent);
        }
    }

    /**
     * 方法名：showLeftTip 功能：左边标识 参数：
     *
     * @param text 文字描述
     * @param url  网址 创建人：huanghaishui 创建时间：2013-12-5
     */
    @JavascriptInterface
    public void showLeftTip(String text, String url) {
        // Log.e("55", text);
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_LEFT_TEXT, text);
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_LEFT_URL, url);
        AppUtil.sendMesToActivity(context, 55, "");
    }

    /**
     * 方法名：showLeftTipMaster 功能：总站提示 参数：
     *
     * @param text
     * @param url  创建人：huanghaishui 创建时间：2014-1-2
     */
    @JavascriptInterface
    public void showLeftTipMaster(String text, String url) {
        // Log.e("57", text);
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_LEFT_TEXT2, text);
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_LEFT_URL2, url);
        AppUtil.sendMesToActivity(context, 57, "");
    }

    @JavascriptInterface
    public void app_sys_info(int param) {
        GaodeLocationManager.startLocation(context, new AMapLocationListener() {

            @Override
            public void onLocationChanged(final AMapLocation location) {
                if (location != null) {
                    TelephonyManager TelephonyMgr = (TelephonyManager) context
                            .getSystemService(Context.TELEPHONY_SERVICE);
                    final String szImei = TelephonyMgr.getDeviceId();
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put(Constant.CITY, location.getCity() + "");
                        jsonObject.put(Constant.LONGITUDE,
                                location.getLongitude() + "");
                        jsonObject.put(Constant.COUNTRY, location.getCountry()
                                + "");
                        jsonObject.put(Constant.PROVINCE,
                                location.getProvince() + "");
                        jsonObject.put(Constant.DISTRICT,
                                location.getDistrict() + "");
                        jsonObject.put(Constant.SZIMEI, szImei);
                        jsonObject.put(Constant.LATITUDE,
                                location.getLatitude() + "");
                        jsonObject.put(Constant.OSVERSION, "android "
                                + android.os.Build.VERSION.RELEASE);
                        jsonObject.put(Constant.NAME, location.getStreet()
                                + location.getStreetNum() + "");
                        jsonObject.put(Constant.MACHINEMODELNAME,
                                android.os.Build.BRAND + " "
                                        + android.os.Build.MODEL);
                        jsonObject.put("astoken",
                                AppUtil.getToken(context));
                        String callback = "app_sys_info_callback";
                        webview.loadUrl("javascript:" + callback + "('"
                                + jsonObject.toString() + "')");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @JavascriptInterface
    public void hidden_app_nav(int param) {
        IndexScreen.isWebControl = true;
        Intent intent = new Intent("com.control.bottombar");
        intent.putExtra("flag", param);
        mactivity.sendBroadcast(intent);
    }

    /**
     * 方法名：showRightTip 功能：右边提示 参数：
     *
     * @param text   文字描述
     * @param url    网址
     * @param number 消息数量 创建人：huanghaishui 创建时间：2013-12-5
     */
    @JavascriptInterface
    public void showRightTip(String text, String url, String number) {
        Log.d("Chenguangxi","tip");
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_RIGHT_TEXT, text);
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_RIGHT_URL, url);
        AppUtil.saveRecord(context, Constant.INDEX_TITLE_RIGHT_NUM, number);
        AppUtil.sendMesToActivity(context, 56, "");
    }

    @JavascriptInterface
    public void setShopKeeperId(String shopKeeperId) {
        AppUtil.saveRecord(context, Constant.shopKeeperId, shopKeeperId);
    }

    @JavascriptInterface
    public void setShopFileId(String shopFileId) {
        AppUtil.saveRecord(context, Constant.shopFileId, shopFileId);
    }

    @JavascriptInterface
    public void setfName(String fName) {
        AppUtil.saveRecord(context, Constant.fName, fName);
    }

    @JavascriptInterface
    public void saveToken(String token) {
        Log.e("save_token", token);
        SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("token",token);
        editor.commit();
    }

    @JavascriptInterface
    public void systemSetting(int pos) {
        mSystemSetPop.show(webview);
    }

    /**
     * 方法名：payMoney 功能： 支付接口 参数：
     *
     * @param merchantName  商户名称
     * @param productName   商品名称
     * @param unitPrice     商品单价
     * @param total         商品数量
     * @param amt           商品总价
     * @param partnerUserId 用户在合作商户的用户名
     * @param orderId       交易订单号 创建人：huanghaishui 创建时间：2014-1-9
     */
    @JavascriptInterface
    public void payMoney(String merchantName, String productName,
                         String unitPrice, String total, String amt, String partnerUserId,
                         String orderId) {
        // 删除数据库中的前一次订单记录
        deleOrderInfo();
        int msgStrId = checkInputInfo(merchantName, productName, unitPrice,
                total, amt, partnerUserId, orderId);
        if (msgStrId == -1) {
            // 新增订单信息
            AppUtil.saveRecord(context, Constant.PAY_ORDER_ID, orderId);
            AppUtil.saveRecord(context, Constant.PAY_AMD, amt);
            AppUtil.saveRecord(context, Constant.PAY_MERCHANT_NAME,
                    merchantName);
            AppUtil.saveRecord(context, Constant.PAY_PROD_NAME, productName);
            AppUtil.saveRecord(context, Constant.PAY_USER_ID, partnerUserId);
            AppUtil.saveRecord(context, Constant.PAY_PRICE, unitPrice);
            AppUtil.saveRecord(context, Constant.PAY_TOTAL, total);
            AppUtil.sendMesToActivity(context, 8888, "");
        } else {
            showToast("订单数据未填写完整，无法支付");
        }
    }

    @JavascriptInterface
    private void deleOrderInfo() {
        AppUtil.deleRecord(context, Constant.PAY_ORDER_ID);
        AppUtil.deleRecord(context, Constant.PAY_AMD);
        AppUtil.deleRecord(context, Constant.PAY_MERCHANT_NAME);
        AppUtil.deleRecord(context, Constant.PAY_PROD_NAME);
        AppUtil.deleRecord(context, Constant.PAY_USER_ID);
        AppUtil.deleRecord(context, Constant.PAY_PRICE);
        AppUtil.deleRecord(context, Constant.PAY_TOTAL);
        AppUtil.deleRecord(context, Constant.PAY_BACK_URL);
    }

    @JavascriptInterface
    private int checkInputInfo(String merchantName, String productName,
                               String unitPrice, String total, String amt, String partnerUserId,
                               String orderId) {

        int msgStrId = -1;

        if (TextUtils.isEmpty(orderId)) {
            msgStrId = 0;
        } else if (TextUtils.isEmpty(amt)) {
            msgStrId = 0;
        } else if (TextUtils.isEmpty(merchantName)) {
            msgStrId = 0;
        } else if (TextUtils.isEmpty(productName)) {
            msgStrId = 0;
        } else if (TextUtils.isEmpty(partnerUserId)) {
            msgStrId = 0;
        } else if (TextUtils.isEmpty(unitPrice)) {
            msgStrId = 0;
        } else if (TextUtils.isEmpty(total)) {
            msgStrId = 0;
        }

        return msgStrId;
    }

    /**
     * 方法名：hiddenTop 功能： 参数： 创建人：huanghaishui 创建时间：2015-11-2
     */
    @JavascriptInterface
    public void hiddenTop() {
        AppUtil.sendMesToActivity(context, 201, "");
    }

    @JavascriptInterface
    public void hiddenBottom() {
        AppUtil.sendMesToActivity(context, 202, "");
    }

    /**
     * 方法名：share 功能：分享 参数：
     *
     * @param title    标题
     * @param content  内容
     * @param webUrl   网页链接地址
     * @param imageUrl 图片地址 创建人：huanghaishui 创建时间：2015-11-3
     */
    @JavascriptInterface
    public void share(String title, String content, String webUrl,
                      String imageUrl, String type) {
        if (StrUtils.isEmpty(title) || StrUtils.isEmpty(content)
                || StrUtils.isEmpty(webUrl) || StrUtils.isEmpty(imageUrl))
            return;
        // if(isShare) return;
        // isShare = true;
        String info = title + ";" + content + ";" + webUrl + ";" + imageUrl
                + ";" + type;
        AppUtil.sendMesToActivity(context, 203, info);
    }

    @JavascriptInterface
    public void saveUserId(String userId) {
        // Log.e("userId", userId);
        AppUtil.saveRecord(context, Constant.USERID, userId);
        // DataUtil.Alert(context, userId);
        AppUtil.sendMesToActivity(context, 205, "");
    }

    /**
     * 方法名：payWxMoney 功能：微信支付 参数：
     *
     * @param productName   商品名称
     * @param price         金额，单位：分
     * @param orderId       订单号
     * @param partnerUserId 用户在合作商户的用户名 创建人：huanghaishui 创建时间：2015-11-4
     */
    @JavascriptInterface
    public void payWxMoney(String productName, String price, String orderId,
                           String partnerUserId, String backUrl) {
        // 删除数据库中的前一次订单记录
        deleOrderInfo();
        // Log.e("pay", productName+"-"+price+"-"+orderId);
        int msgStrId = -1;
        if (StrUtils.isEmpty(productName) || StrUtils.isEmpty(price)
                || StrUtils.isEmpty(orderId) || StrUtils.isEmpty(partnerUserId)) {
            msgStrId = 0;

        }
        if (msgStrId == -1) {
            AppUtil.saveRecord(context, Constant.PAY_ORDER_ID, orderId);
            AppUtil.saveRecord(context, Constant.PAY_USER_ID, partnerUserId);

            AppUtil.saveRecord(context, Constant.PAY_AMD, price);
            AppUtil.saveRecord(context, Constant.PAY_PROD_NAME, productName);
            AppUtil.saveRecord(context, Constant.PAY_BACK_URL, backUrl);

            new WXPayUtil(context, productName, price, orderId).goPay();
        } else {
            showToast("订单数据未填写完整，无法支付");
        }
    }

    /**
     * 方法名：payZfbMoney 功能：支付宝支付 参数：
     *
     * @param productName   商品名称
     * @param price         金额 单位：元
     * @param orderId       订单号
     * @param partnerUserId 用户在合作商户的用户名 创建人：huanghaishui 创建时间：2015-11-5
     */
    @JavascriptInterface
    public void payZfbMoney(String productName, String price, String orderId,
                            String partnerUserId, String backUrl) {
        // 删除数据库中的前一次订单记录
        deleOrderInfo();
        // Log.e("pay", productName+"-"+price+"-"+orderId);
        int msgStrId = -1;
        if (StrUtils.isEmpty(productName) || StrUtils.isEmpty(price)
                || StrUtils.isEmpty(orderId) || StrUtils.isEmpty(partnerUserId)) {
            msgStrId = 0;
        }
        if (msgStrId == -1) {
            AppUtil.saveRecord(context, Constant.PAY_ORDER_ID, orderId);
            AppUtil.saveRecord(context, Constant.PAY_USER_ID, partnerUserId);
            AppUtil.saveRecord(context, Constant.PAY_AMD, price);
            AppUtil.saveRecord(context, Constant.PAY_PROD_NAME, productName);
            AppUtil.saveRecord(context, Constant.PAY_BACK_URL, backUrl);
            new AliPayUtil(context, mactivity, productName, price, orderId)
                    .goPay();
        } else {
            showToast("订单数据未填写完整，无法支付");
        }
    }

    @JavascriptInterface
    public void qrCodeLogin(String method) {
        Intent intent = new Intent(context, MipcaActivityCapture.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("method", method);
        ((Activity) context).startActivityForResult(intent, 2);
    }

    @JavascriptInterface
    public void is_callback(int exit) {
        if (1 == exit) {
            IndexScreen.isCallback = true;
            // AppUtil.sendMesToActivity(context, 5321, "1");
        }
    }

    @JavascriptInterface
    public void app_outside_login(int platform) {
        AppUtil.sendMesToActivity(context, 366, platform + "");

    }

    @JavascriptInterface
    public void android_scroll_vertical_ctrl(String v) {
        AppUtil.sendMesToActivity(context, 466, v);
    }

    @JavascriptInterface
    public void is_zoom_screen(int flag) {
        AppUtil.sendMesToActivity(context, 501, flag + "");
    }

    @JavascriptInterface
    public void is_check_network(String json) {
        if(!mIsChecking){
            try {
                json = URLDecoder.decode(json, "utf-8");
                Log.d("ChenguangxiResult",json);
                final JSONObject jsonObject = new JSONObject(json);
                String isCheck = jsonObject.getString("is_check");
                final String callback = jsonObject.getString("callback");
                if (isCheck.equals("1")) {
                    JSONArray jsonArray = jsonObject.getJSONArray("url");
                    if(jsonArray!=null){
                        mIsChecking = true;
                        diagnose(jsonArray,callback,-1,true);
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            Toast.makeText(context,"正在检测",Toast.LENGTH_SHORT).show();
        }
    }

    @JavascriptInterface
    public void is_check_network_close(int flag){
        if(flag == 1){
            if(mLdDiagnoService!=null){
                mLdDiagnoService.stopNetDialogsis();
                mIsChecking = false;
            }
        }
    }

    private void diagnose(final JSONArray jsonArray, final String callback, final int pos , boolean isBaseData){
        if(jsonArray!=null){
            JSONObject daname = null;
            String domainName;
            final int count = jsonArray.length();
            try {
                if(pos>=0){
                    daname = jsonArray.getJSONObject(pos);
                    domainName = daname.getString("daname");
                }else{
                    domainName = "";
                }
                mLdDiagnoService = NetDiagnosesUtil.startDiagnoses(context, domainName, new LDNetDiagnoListener() {
                    @Override
                    public void OnNetDiagnoFinished(String log) {
                        mDiagnoseLog+=log;
                        if(pos == count - 1){
                            postDiagnoseData(mDiagnoseLog,context);
                            mIsChecking = false;
                        }else{
                            diagnose(jsonArray,callback,pos+1,false);
                        }
                    }

                    @Override
                    public void OnNetDiagnoUpdated(String log) {
                        webview.loadUrl("javascript:" + callback + "('"
                                + log + "')");
                    }
                },isBaseData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private static void postDiagnoseData(final String log, final Context context) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("get_data",log);
                    jsonObject.put("flag","0");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                HttpService.getInstance(context).postNetDiagnoseData(jsonObject);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {

            }
        });
    }

    @JavascriptInterface
    public void is_exit(int flag) {
        if (flag == 1) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    int i = 3 / 0;
                }
            });
        }
    }

}